﻿using System;
using System.Collections.Generic;
using System.Linq;
using Coder.Workflow;

namespace Coder.Workflow
{
    public class WorkTaskCompare : IComparer<WorkTask>
    {
        public int Compare(WorkTask x, WorkTask y)
        {
            return x.Ordered.CompareTo(y.Ordered);
        }
    }

    public abstract class WorkProcess
    {
        private SortedSet<WorkTask> _items;

        public int Id { get; set; }
        public string Name { get; set; }

        public IEnumerable<WorkTask> Items
        {
            get => _items ?? (_items = new SortedSet<WorkTask>(new WorkTaskCompare()));
            set
            {
                if (value != null)
                {
                    var list = Items as SortedSet<WorkTask>;
                    foreach (var item in list) list.Add(item);
                }
                else
                {
                    _items?.Clear();
                }
            }
        }

        public string WorkflowType { get; protected set; }

        protected virtual void Add(WorkTask task)
        {
            if (task == null) throw new ArgumentNullException(nameof(task));
            if (task.Name == null)
                throw new ArgumentNullException(nameof(task), "task.Name can't be null.");
            var list = Items as SortedSet<WorkTask>;
            if (task.Ordered == -1) task.Ordered = Items.Count();
            list.Add(task);
        }

        internal WorkTask Start()
        {
            var list = Items as SortedSet<WorkTask>;
            return list.First();
        }

        public bool TryGetNext(int currentStepId, out IEnumerable<WorkTask> nextWrokWorkTask)
        {
            var orderedId = -1;
            nextWrokWorkTask = null;
            var task = new List<WorkTask>();


            foreach (var item in Items)
            {
                if (item.Id == currentStepId)
                {
                    orderedId = item.Ordered + 1;
                    continue;
                }

                if (item.Ordered == orderedId) task.Add(item);
            }

            if (task.Any())
                nextWrokWorkTask = task;


            return nextWrokWorkTask != null;
        }


        internal bool TryGetPrevious(WorkTask currentTask, out WorkTask previouWorkTask)
        {
            previouWorkTask = null;
            var currentTaskId = currentTask.Id;
            foreach (var item in Items)
            {
                if (item.Id == currentTaskId) return previouWorkTask != null;

                previouWorkTask = item;
            }


            return false;
        }
    }

    public abstract class WorkProcess<T> : WorkProcess where T : WorkTask
    {
        public void Add(T task)
        {
            base.Add(task);
        }
    }
}